<template>
  <basic-container :btnFlag=true>
    <div class="card-border">
      <card-header :header-data="headerData"></card-header>
      <!-- 搜索栏 -->
      <form class="el-form el-form--inline avue-crud__search" style="margin: 14px 0px -7px 15px">
        <div class="el-form-item">
          <label class="el-form-item__label">课题名称:</label>
          <div class="el-form-item__content">
            <el-input v-model="plantitle" size="small" placeholder="请输入内容" clearable></el-input>
          </div>
        </div>
        <div class="el-form-item avue-crud__searchMenu">
          <div class="el-form-item__content">
            <el-button class="myBtn" type="primary" icon="el-icon-search" @click.stop="searchSubmit()">搜索</el-button>
            <el-button class="myBtn" type="reset" icon="el-icon-delete" @click.stop="resetSubmit()" >重置</el-button>
            <!--<el-button type="warning" size="small" @click.stop="searchSubmit()">查询</el-button>-->
          </div>
        </div>
      </form>
      <div style="float: right;margin:19px 12px 9px 0px">
        <el-button type="primary" size="mini" @click="subjectLevyResult()">课题征集</el-button>
        <el-button type="success" size="mini" @click="draftSubjectPlan()">增补课题</el-button>
        <el-button type="warning" size="mini" @click="exportSubjectExcel()">导出</el-button>
      </div>
      <div class="card-body">
        <el-table
          :data="tableData"
          style="width: 100%"
          row-key="id"
          :row-class-name="tableRowClassName"
          border
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          @selection-change="handleSelectionChange"
          ref="subjectTreeTable">
          <el-table-column
            align="left"
            prop="mainTitle"
            label="名称"
            width="420"
            class="turn_to_inline">
            <template slot-scope="scope">
              <el-popover
                placement="top-start"
                title="课题名称:"
                width="400"
                trigger="hover"
                :content="scope.row.mainTitle"
                v-if="scope.row.isChild">
                <a style="cursor:pointer;line-height: 15px;margin-left: 40px"
                   @click="subjectDetail(scope.row.subjectId)" slot="reference"
                   class="single_line_hidden">{{scope.row.mainTitle}}</a>
              </el-popover>
              <el-popover
                placement="top-start"
                title="规划名称:"
                width="400"
                trigger="hover"
                :content="scope.row.mainTitle"
                v-if="!scope.row.isChild">
                <span slot="reference" class="single_line_hidden"
                      @click="detailDialog(scope.row.achievementId,scope.row.pmuc)"
                      style="cursor:pointer;line-height: 15px;display:inline-block;font-weight: bold;width: 80%">
                  {{scope.row.mainTitle}}
                </span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="deptName"
            label="牵头单位"
            width="120">
          </el-table-column>
          <el-table-column
            align="center"
            prop="supportDeptName"
            label="配合单位">
          </el-table-column>
          <el-table-column
            align="center"
            prop="state"
            label="状态"
            :formatter="formatterState">
          </el-table-column>
          <el-table-column
            align="center"
            width="210">
            <template slot="header" slot-scope="scope">
              <span>操作</span>
            </template>
            <template slot-scope="scope">
              <div class="menu-title" @click.stop="editSubject(scope.row,scope.index)"
                   v-if="scope.row.isChild && scope.row.state=='0'">
                <i class="iconfont iconalter icon-warning"></i>
                <p class="menu-title-text">列入计划</p>
              </div>
              <div class="menu-title" @click.stop="preparationPlan(scope.row,scope.index)"
                   v-if="!scope.row.isChild">
                <i class="iconfont iconview icon-primary"></i>
                <p class="menu-title-text">编制计划</p>
              </div>
              <div class="menu-title" @click.stop="selectPlan(scope.row,'0')"
                   v-if="!scope.row.isChild">
                <i class="iconfont iconalter icon-warning"></i>
                <p class="menu-title-text">征求意见</p>
              </div>
              <div class="menu-title" @click.stop="selectPlan(scope.row,'1')"
                   v-if="!scope.row.isChild">
                <i class="iconfont iconview icon-primary"></i>
                <p class="menu-title-text">修改计划</p>
              </div>
              <div class="menu-title" @click.stop="selectPlan(scope.row,'2')"
                   v-if="!scope.row.isChild">
                <i class="iconfont iconalter icon-warning"></i>
                <p class="menu-title-text">下达计划</p>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[1, 2, 5, 10, 20, 30, 40 ,50]"
            :current-page="page.currentPage"
            :page-size="page.pageSize"
            :total="page.total"
            layout="total, sizes, prev, pager, next, jumper"
            class="paginationcss">
          </el-pagination>
        </div>
      </div>
      <el-dialog title="选择计划" :visible.sync="dialogVisible" width="1000px">
        <div class="card-body" style="padding-bottom: 0px;position:relative;">
          <avue-crud :data="planListData"
                     :option="planListOption"
                     :page="planListpage"
                     :table-loading="planListtableLoading"
                     @on-load="getResultList"
                     @refresh-change="refreshChange"
                     @search-change="searchChange"
                     class="avuecrud">
            <template slot-scope="scope" slot="menu">
              <div class="menu-title" @click.stop="planningForComments(scope.row,scope.index)"
                   v-if="typetemp=='0'&&scope.row.state!='1'">
                <i class="iconfont iconview icon-primary"></i>
                <p class="menu-title-text">征求意见</p>
              </div>
              <div class="menu-title" @click.stop="plaitReportHistory(scope.row,scope.index)"
                   v-if="typetemp=='0'&&scope.row.state=='1'">
                <i class="iconfont iconview icon-primary"></i>
                <p class="menu-title-text">查看反馈</p>
              </div>
              <div class="menu-title" @click.stop="modifyPlan(scope.row,scope.index)"
                   v-if="typetemp=='1'">
                <i class="iconfont iconview icon-primary"></i>
                <p class="menu-title-text">修改计划</p>
              </div>
              <div class="menu-title" @click.stop="releasePlan(scope.row,scope.index)"
                   v-if="typetemp=='2'">
                <i class="iconfont iconview icon-primary"></i>
                <p class="menu-title-text">下达计划</p>
              </div>
            </template>
          </avue-crud>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible=false">取 消</el-button>
          </div>
        </div>
      </el-dialog>
      <el-dialog title="编制计划" :visible.sync="dialogVisiblePlan" width="1000px"
                 @close="$refs.waitPlanListData.toggleSelection()">
        <div class="card-body" style="padding-bottom: 0px;position:relative;">
          <avue-crud :data="waitPlanListData"
                     :option="waitPlanListOption"
                     :table-loading="waitPlanListtableLoading"
                     @selection-change="selectionChange"
                     @size-change="sizeChangeWait"
                     @current-change="currentChangeWait"
                     class="avuecrud"
                     ref="waitPlanListData">
          </avue-crud>
        </div>
        <div slot="footer" class="dialog-footer" style="margin-bottom: 10px;">
          <el-button type="primary" @click="confirmWaitPlan()">编制计划</el-button>
          <el-button @click="dialogVisiblePlan=false">取 消</el-button>
        </div>
      </el-dialog>
      <detail-dialog :achievementId="achievementIdDD"
                     :pmuc="pmucDD"
                     :showDetailDialog.sync="showDetailDialog"
                     :key="achievementIdDD"></detail-dialog>

      <el-dialog title="课题详情" :visible.sync="dialogVisibleSubject" width="1000px">
        <bostech-detail :detail-data="detailDataSubject" style="padding-top: 0px;"></bostech-detail>
        <div slot="footer" class="dialog-footer" style="padding-bottom: 20px">
          <el-button @click="dialogVisibleSubject = false">关 闭</el-button>
        </div>
      </el-dialog>

    </div>
  </basic-container>
</template>

<script>
  import {getSubjectTreeList, getPlanList, getSubjectList,exportSubjectExcel} from "@/api/subject";
  import relatedfile from "@/mixins/relatedfile";
  import {getOpinionList} from "@/api/opinion";
  import {getSubjectInfo} from "@/api/subject";
  import {getNotNull} from '@/views/util'

  export default {
    name: "subjectPlanList",
    mixins: [relatedfile],
    watch: {},
    created() {
      var self = this;
      window.subjectDetail = self.subjectDetail;
      window.detailDialog = self.detailDialog;
      this.putTableData();
      this.getWaitResultList()
    },
    data() {
      return {
        headerData: {
          title: '课题计划'
        },
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 5 // 每页显示多少条
        },
        formatterTime: function (row, value, label, column) {
          if (row.joinTime != null) {
            var data = row.joinTime.split(' ');
            return data[0];
          }
        },
        formatterState: function (row, value, label, column) {
          if (row.state == '0') {
            return '拟定';
          } else if (row.state == '1') {
            return '待编制';
          } else if (row.state == '2') {
            return '已编制';
          } else if (row.state == '3') {
            return '征求意见';
          } else if (row.state == '4') {
            return '已下达';
          } else if (row.state == '5') {
            return '报告已上传';
          } else if (row.state == '6') {
            return '成果征求意见';
          } else if (row.state == '7') {
            return '结题申请';
          } else if (row.state == '8') {
            return '结题申请未通过';
          } else if (row.state == '9') {
            return '已发布';
          }
        },
        achievementIdForcheck: 0,
        selectedSubjectIds: [],
        dialogVisible: false,
        planListData: [],
        planListpage: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 5 // 每页显示多少条
        },
        planListOption: {
          page: true,
          menuWidth: 120,
          addBtn: false,
          editBtn: false,
          addRowBtn: false,
          indexLabel: "序号",
          index: true,
          indexWidth:70,
          cellBtn: false,
          delBtn: false,
          columnBtn: false,
          refreshBtn: false,
          filterBtn: false,
          searchBtn: false,
          keyId: "id",
          column: [
            {
              label: "计划名称",
              prop: "title",
              cell: true,
            },
            {
              label: "编制时间",
              width: 130,
              prop: "createTime",
              cell: true,
              formatter: function (row, value, label, column) {
                if (value) {
                  return value.split(' ')[0]
                }
                return value;
              },
            },
            {
              label: "状态",
              prop: "state",
              width: 120,
              cell: true,
              dicData: [
                {
                  label: '已编制',
                  value: '0',
                },
                {
                  label: '征求意见',
                  value: '1',
                }]
            },
          ]
        },
        planListtableLoading: false,
        typetemp: '',
        plantitle: '',
        dialogVisiblePlan: false,
        waitPlanListData: [],
        waitPlanListtableLoading: false,
        waitPlanListOption: {
          page: false,
          menuWidth: 120,
          addBtn: false,
          editBtn: false,
          addRowBtn: false,
          indexLabel: "序号",
          index: true,
          indexWidth:70,
          cellBtn: false,
          delBtn: false,
          columnBtn: false,
          refreshBtn: false,
          filterBtn: false,
          searchBtn: false,
          selection: true,
          menu: false,
          keyId: "id",
          column: [
            {
              label: "课题名称",
              prop: "title",
              cell: true,
            },
            {
              label: "创建时间",
              width: 130,
              prop: "createTime",
              cell: true,
              formatter: function (row, value, label, column) {
                if (value) {
                  return value.split(' ')[0]
                }
                return value;
              },
            },
            {
              label: "状态",
              prop: "state",
              width: 120,
              cell: true,
              dicData: [
                {
                  label: '待编制',
                  value: '1',
                }
              ]
            },
          ]
        },
        waitPlanListpage: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        achievementIdWait: null,
        achievementTitleWait: null,
        achievementIdDD: null,
        pmucDD: null,
        showDetailDialog: null,
        dialogVisibleSubject: false,
        detailDataSubject:[
          {label: '课题名称', value: ''},
          {label: '课题概述', value: ''},
          {label: '创建时间', value: ''},
        ],

      }
    },
    methods: {
      // 课题征集结果跳转
      subjectLevyResult() {
        let src = `/subjectLevyResult/detail`;
        this.$router.push({
          path: src
        })
      },
      // 课题详情跳转
      draftSubjectPlan() {
        sessionStorage.setItem('draftSubjectPlan.achievementTitle', '');
        sessionStorage.setItem('draftSubjectPlan.achievementId', '');
        sessionStorage.setItem('draftSubjectPlan.title', '');
        sessionStorage.setItem('draftSubjectPlan.description', '');
        let src = `/draftSubjectPlan/index`;
        this.$router.push({
          path: src
        })
      },
      // 编辑课题跳转
      editSubject(row) {
        let src = `/editSubject/detail/${row.subjectId}`;
        this.$router.push({
          path: src
        })
      },
      // 课题详情跳转
      subjectDetail(subjectId) {
        this.dialogVisibleSubject = true;
        getSubjectInfo(subjectId).then(async response => {
          let records =await response.data.data;
          this.detailDataSubject = [
            {label: '课题名称', value: getNotNull(records.title)},
            {label: '课题概述', value: getNotNull(records.description)},
            {label: '创建时间', value: getNotNull(records.createTime)},
          ]

        });
      },
      // 征求意见跳转
      planningForComments(row) {
        let src = `/planningForComments/detail/${row.planId}`;
        this.$router.push({
          path: src,
          query: {
            title: row.title,
            createTime: row.createTime,
            achievementTitle: row.achievementTitle,
            orgName: row.orgName
          }
        })
      },
      // 修改计划跳转
      modifyPlan(row) {
        let src = `/modifyPlan/detail/${row.planId}`;
        this.$router.push({
          path: src,
          query: {
            achievementId: row.achievementId,
            title: row.title,
            description: row.description,
            createTime: row.createTime,
            achievementTitle: row.achievementTitle,
          }
        })
      },
      // 下达计划跳转
      releasePlan(row) {
        let src = `/releasePlan/detail/${row.planId}`;
        this.$router.push({
          path: src,
          query: {
            achievementId: row.achievementId,
            title: row.title,
            description: row.description,
            createTime: row.createTime,
            achievementTitle: row.achievementTitle,
          }
        })
      },
      putTableData() {
        getSubjectTreeList(Object.assign({
          current: this.page.currentPage,
          size: this.page.pageSize,
          achievementStates:'0,1,2'
        })).then(response => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
        })
      },
      pageputTableData(page) {
        getSubjectTreeList(Object.assign({
          current: page.currentPage,
          size: page.pageSize,
          achievementStates:'0,1,2'
        })).then(response => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
        })
      },
      searchSubmit(){
        this.planListpage.currentPage = 1
        this.putTableDataByTitle(this.plantitle)
      },
      resetSubmit(){
        this.plantitle= '';
        this.putTableDataByTitle()
      },
      handleSizeChange(val) {
        let page = this.planListpage;
        page.pageSize = val;
        this.putTableDataByTitle(this.plantitle);
      },
      handleCurrentChange(val) {
        let page = this.planListpage;
        page.currentPage = val;
        this.putTableDataByTitle(this.plantitle);
      },
      currentChangeWait(currentPage) {
        let page = this.waitPlanListpage;
        page.currentPage = currentPage;
        let params={titleLike: this.plantitle};
        this.putTableDataByTitle(page,params);
      },
      sizeChangeWait(pageSize) {
        let page = this.waitPlanListpage;
        page.pageSize = pageSize;
        let params={titleLike: this.plantitle};
        this.putTableDataByTitle(page,params);
      },
      tableRowClassName({row, rowIndex}) {
        if (row.state == undefined) {
          return 'success-row';
        }
        return '';
      },
      handleSelectionChange(val) {
        if (val.length == 1) {
          this.achievementIdForcheck = val[0].achievementId;
        }
        if (val.length != 0) {
          for (var item in this.tableData) {
            if (this.tableData[item].achievementId != this.achievementIdForcheck) {
              this.$refs.subjectTreeTable.toggleRowSelection(this.tableData[item], false);
              if (this.tableData[item].children.length != 0) {
                for (var itemcd in this.tableData[item].children) {
                  if (this.tableData[item].children[itemcd].achievementId != this.achievementIdForcheck) {
                    this.$refs.subjectTreeTable.toggleRowSelection(this.tableData[item].children[itemcd], false);
                  }
                }
              }
            }
          }
        } else {
          this.achievementIdForcheck = 0;
          this.selectedSubjectIds = [];
        }
        if (val.length != 0) {
          this.selectedSubjectIds = [];
          for (var item in val) {
            this.selectedSubjectIds.push(val[item].subjectId)
          }
        }

      },
      checkboxT(row) {
        if (!row.isChild || row.state != '1') {
          return false;
        } else {
          return true;
        }
      },
      //用于选择计划然后跳转到征求意见0，修改计划1或者下达计划2
      async selectPlan(row, type) {
        this.dialogVisible = true;
        this.planListtableLoading = true;
        this.typetemp = type;
        var typecontrol = '0,1';
        await getPlanList(Object.assign({
          achievementId: row.achievementId,
          states: typecontrol,
        })).then(response => {
          this.planListData = response.data.data.records;
          this.planListtableLoading = false;
        });
      },
      getResultList() {

      },
      refreshChange() {

      },
      searchChange() {

      },
      // 版本管理
      plaitReportHistory(row, index) {
        getOpinionList(Object.assign({
          current: 0,
          size: 10,
          relateId: row.planId,
          type: '1'
        })).then(response => {
          let records = response.data.data.records;
          if (records && records.length > 0) {
            let row = records[0];
            let src = `/collectionListPlan/list/${row.relateId}`;
            this.$router.push({
              path: src,
              query: {
                type: '1',
                title: row.achievementTitle,
              }
            })
          } else {
            this.$notify({
              title: "提醒",
              type: "warning",
              message: "暂无征求意见！",
              duration: 2000
            });
          }
        })
      },
      // 编制计划跳转
      async preparationPlan(row) {
        this.dialogVisiblePlan = true;
        this.waitPlanListtableLoading = true;
        this.achievementIdWait = row.achievementId;
        this.achievementTitleWait = row.achievementTitle;
        await getSubjectList(Object.assign({
          current: 1,
          size: -1,
          achievementId: row.achievementId,
          states: 1,
        })).then(response => {
          this.waitPlanListData = response.data.data.records;
          this.waitPlanListtableLoading = false;
          this.waitPlanListpage.total = response.data.data.total;
        });

      },

      getWaitResultListPage(page) {
        getSubjectList(Object.assign({
          current: page.currentPage,
          size: -1,
          achievementId: this.achievementIdWait,
          states: 1,
        })).then(response => {
          this.waitPlanListData = response.data.data.records;
          this.waitPlanListtableLoading = false;
          this.waitPlanListpage.total = response.data.data.total;
        });
      },
      getWaitResultList() {

      },
      selectionChange(list) {
        if (list.length != 0) {
          this.selectedSubjectIds = [];
          for (var item in list) {
            this.selectedSubjectIds.push(list[item].subjectId)
          }
        }
      },
      confirmWaitPlan() {
        if (this.selectedSubjectIds.length == 0) {
          this.$notify({
            title: "提醒",
            type: "warning",
            message: "请选择课题！",
            duration: 2000
          });

        } else {
          this.dialogVisiblePlan = false;
          let src = `/preparationPlan/detail/${this.achievementIdWait}`;
          this.$router.push({
            path: src,
            query: {
              achievementTitle: this.achievementTitleWait,
              selectedSubjectIds: this.selectedSubjectIds.join(',')
            }
          })
        }
      },
      detailDialog (achievementId,pmuc) {
        this.achievementIdDD = achievementId;
        this.pmucDD = pmuc;
        this.showDetailDialog = true;
      },
      indexMethod(index) {
        return index;
      },

//      currentChangeWait(currentPage) {
//        let page = this.waitPlanListpage;
//        page.currentPage = currentPage;
//        let params={titleLike: this.plantitle}
//        this.putTableDataByTitle(page,params);
//      },
//      sizeChangeWait(pageSize) {
//        let page = this.waitPlanListpage;
//        page.pageSize = pageSize;
//        let params={titleLike: this.plantitle}
//        this.putTableDataByTitle(page,params);
//      },
      putTableDataByTitle(titleLike) {
        getSubjectTreeList(Object.assign({
          current: this.planListpage.currentPage,
          size: this.planListpage.pageSize,
          achievementStates:'0,1,2',
          titleLike:titleLike
        })).then(response => {
          this.tableData = response.data.data.records;
//          this.page = {
//            total: 0, // 总页数
//            currentPage: 1, // 当前页数
//            pageSize: 10 // 每页显示多少条
//          };
          this.page.total = response.data.data.total;
        })
      },
      exportSubjectExcel(){
        this.$confirm("确定要导出课题列表吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=>{
          exportSubjectExcel(Object.assign({
            states:'0,1,2,3,4,5,6,7,8,9',
            achievementStates:'0,1,2'
          })).then(response => {
            let exportFileName = "课题列表.xlsx";
            this.download(response.data, exportFileName)
          })
        })
      },
      // 下载文件
      download(data, filename) {
        if (data == null) {

        } else {
          let url = window.URL.createObjectURL(new Blob([data]));
          let link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', filename);
          document.body.appendChild(link);
          link.click()
        }
      },


    }
  }
</script>

<style lang="scss" scoped>
  .card-body {
    padding: 10px;
    padding-bottom: 65px;
  }

  .paginationcss {
    margin-top: 20px;
    float: right;
    margin-right: 28px;
  }

  .form-item {
    font-weight: 600;
  }

  .dialog-footer {
    margin-left: 417px;
    position: absolute;
    bottom: 0;
  }
  .myBtn{
    padding: 8px 15px;
    font-size: 14px;
    border-radius: 3px;
  }
</style>


